/*
 * XXX
 */

package edu.uhcl.csci4838.group3.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import edu.uhcl.csci4838.group3.R;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorTask;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorTaskAlert;
import edu.uhcl.csci4838.group3.database.info.Task;
import edu.uhcl.csci4838.group3.database.info.TaskAlert;
import edu.uhcl.csci4838.group3.view.help.HelpActivity;

/**
 * XXX
 * 
 * @author Chris Waguespack
 */
public class TaskActivity extends Activity {
	/**
	 * XXX
	 * 
	 * @author Chris Waguespack
	 */
	private static class AlertViewBinder implements
			SimpleCursorAdapter.ViewBinder {
		
		/**
		 * XXX
		 */
		public AlertViewBinder() {
			// TODO Auto-generated constructor stub
		}
		
		/**
		 * XXX
		 * 
		 * @param view
		 *            XXX
		 * @param cursor
		 *            XXX
		 * @param columnIndex
		 *            XXX
		 * @return XXX
		 */
		/* 
		 * (non-Javadoc)
		 * 
		 * @see android.widget.SimpleCursorAdapter.ViewBinder#setViewValue(android.view.View, android.database.Cursor, int)
		 */
		@Override
		public boolean setViewValue(final View view,
				final Cursor cursor,
				final int columnIndex) {
			switch (view.getId()) {
				case R.id.tv_minutesBefore:
					final int minutes = ((CursorTaskAlert) cursor).getColMinutesBefore();
					final StringBuilder timeString = new StringBuilder();
					if (minutes >= 1440) {
						// Show days
						timeString.append(minutes / 1440);
						timeString.append(" d - ");
					}
					if (minutes >= 60) {
						// Show hours
						timeString.append((minutes % 1440) / 60);
						timeString.append(" h - ");
					}
					// Show minutes
					timeString.append((minutes % 1440) % 60);
					timeString.append(" m before");
					
					((TextView) view).setText(timeString.toString());
					return true;
				default:
					return false;
			}
		}
	}
	
	/**
	 * The database helper object.
	 */
	private static BackpackEduDatabaseHelper dbHelper;
	
	/**
	 * The task cursor used to populate this view.
	 */
	private CursorTask taskCursor;
	
	private static TextView tvCourseName;
	private static TextView tvTaskName;
	private static TextView tvCategory;
	private static CheckBox cbCompleted;
	private static TextView tvDueDate;
	private static TextView tvReceivedGrade;
	private static TextView tvMaxGrade;
	private static TextView tvWeightOverride;
	private static ListView lvAlerts;
	
	/**
	 * XXX
	 * 
	 * @param menu
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		this.getMenuInflater()
				.inflate(R.menu.options_task,
						menu);
		return true;
	}
	
	/**
	 * XXX
	 * 
	 * @param item
	 *            XXX
	 * @return XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_item_edit_task:
				this.startActivity(new Intent(this.getApplicationContext(),
						EditTaskActivity.class).putExtra(this.getString(R.string.intent_extra_taskId),
						this.taskCursor.getColId()).putExtra(this.getString(R.string.intent_extra_courseId), this.taskCursor.getColCourseId()));
				return true;
			case R.id.menu_item_delete_task:
				this.showDeleteTaskDialog();
				return true;
			case R.id.menu_item_settings:
				this.startActivity(new Intent(this.getApplicationContext(),
						SettingsActivity.class));
				return true;
			case R.id.menu_item_about:
				this.startActivity(new Intent(this.getApplicationContext(),
						AboutActivity.class));
				return true;
			case R.id.menu_item_help:
				this.startActivity(new Intent(this.getApplicationContext(),
						HelpActivity.class));
				return true;
			default:
				Log.wtf("BackpackEDU",
						"Undefined options menu item.");
				return super.onOptionsItemSelected(item);
		}
	}
	
	/**
	 * XXX
	 * 
	 * @param savedInstanceState
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.ActivityGroup#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		this.setContentView(R.layout.activity_view_task);
		
		// Get components
		TaskActivity.tvCourseName = (TextView) this.findViewById(R.id.textView_courseName);
		TaskActivity.tvTaskName = (TextView) this.findViewById(R.id.textView_taskName);
		TaskActivity.tvCategory = (TextView) this.findViewById(R.id.textView_category);
		TaskActivity.cbCompleted = (CheckBox) this.findViewById(R.id.cb_completed);
		TaskActivity.tvDueDate = (TextView) this.findViewById(R.id.textView_displayDate);
		TaskActivity.tvReceivedGrade = (TextView) this.findViewById(R.id.textView_receivedGrade);
		TaskActivity.tvMaxGrade = (TextView) this.findViewById(R.id.textView_maxGrade);
		TaskActivity.tvWeightOverride = (TextView) this.findViewById(R.id.textView_weightOverride);
		TaskActivity.lvAlerts = (ListView) this.findViewById(R.id.lv_alerts);
		
		// Calling intent
		final Intent callingIntent = this.getIntent();
		final long taskId = callingIntent.getLongExtra(this.getString(R.string.intent_extra_taskId),
				-1);
		
		// Cursor
		TaskActivity.dbHelper = new BackpackEduDatabaseHelper(this);
		ContentValues criteria = new ContentValues();
		criteria.put(Task.ID,
				Long.valueOf(taskId));
		this.taskCursor = TaskActivity.dbHelper.getTask(criteria,
				null,
				true);
		this.startManagingCursor(this.taskCursor);
		
		// Populate the fields
		TaskActivity.tvCourseName.setText(this.taskCursor.getColCourseName());
		TaskActivity.tvTaskName.setText(this.taskCursor.getColName());
		TaskActivity.tvCategory.setText(this.taskCursor.getColCategoryName());
		
		// Completed
		TaskActivity.cbCompleted.setChecked(this.taskCursor.getColIsCompleted());
		TaskActivity.cbCompleted.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			/**
			 * XXX
			 * 
			 * @param buttonView
			 * @param isChecked
			 */
			/* 
			 * (non-Javadoc)
			 * 
			 * @see android.widget.CompoundButton.OnCheckedChangeListener#onCheckedChanged(android.widget.CompoundButton, boolean)
			 */
			@Override
			public void onCheckedChanged(final CompoundButton buttonView,
					final boolean isChecked) {
				final ContentValues completedCriteria = new ContentValues(1);
				completedCriteria.put(Task.IS_COMPLETED,
						Boolean.valueOf(isChecked));
				TaskActivity.dbHelper.editTask(taskId,
						completedCriteria);
			}
		});
		
		// Due Date
		if ((this.taskCursor.getColDateDue() == null)) {
			this.findViewById(R.id.layout_dueDate)
					.setVisibility(View.GONE);
		} else {
			final long date = this.taskCursor.getColDateDue()
					.longValue();
			TaskActivity.tvDueDate.setText(DateFormat.format("MM/dd/yy",
					date));
		}
		
		// Grade
		TaskActivity.tvReceivedGrade.setText(this.taskCursor.getColReceivedGrade() == null
				? "-"
				: this.taskCursor.getColReceivedGrade()
						.toString());
		TaskActivity.tvMaxGrade.setText(this.taskCursor.getColMaxGrade() == null
				? "-"
				: this.taskCursor.getColMaxGrade()
						.toString());
		
		// WeightOverride
		if ((this.taskCursor.getColWeightOverride() == null)) {
			this.findViewById(R.id.layout_weightOverride)
					.setVisibility(View.GONE);
		} else {
			TaskActivity.tvWeightOverride.setText(this.taskCursor.getColWeightOverride()
					.toString());
		}
		
		// Alerts
		criteria = new ContentValues();
		criteria.put(TaskAlert.TASK_ID,
				taskId);
		final CursorTaskAlert taskAlertCursor = TaskActivity.dbHelper.getTaskAlert(criteria,
				new String[] { TaskAlert.MINUTES_BEFORE },
				true);
		this.startManagingCursor(taskAlertCursor);
		if (taskAlertCursor.getCount() < 1) {
			this.findViewById(R.id.layout_alerts)
					.setVisibility(View.GONE);
		} else {
			// Set up the adapter
			final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
					R.layout.item_alert,
					taskAlertCursor,
					new String[] { TaskAlert.MINUTES_BEFORE },
					new int[] { R.id.tv_minutesBefore });
			adapter.setViewBinder(new AlertViewBinder());
			TaskActivity.lvAlerts.setAdapter(adapter);
		}
	}
	
	/**
	 * XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		TaskActivity.dbHelper.close();
		super.onDestroy();
	}
	
	/**
	 * XXX
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	protected void onRestart() {
		super.onRestart();
		// TODO Q&D fix to get it working
		this.taskCursor.moveToFirst();
	}
	
	/**
	 * XXX
	 */
	private void showDeleteTaskDialog() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.menu_title_delete_task)
				.setMessage("Are you sure you want to delete the task \""
						+ this.taskCursor.getColName()
						+ "\" ?")
				.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							
							@SuppressWarnings("synthetic-access")
							@Override
							public void onClick(final DialogInterface dialog,
									final int which) {
								TaskActivity.dbHelper.deleteTask(TaskActivity.this.taskCursor.getColId());
								TaskActivity.this.finish();
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new CancelListener());
		final AlertDialog alert = builder.create();
		alert.show();
	}
}
